import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sonora/utils/sj_medal_utils.dart';
import 'package:sonora/utils/sj_storage_utils.dart';
import 'package:sonora/utils/sj_text_style.dart';
import 'package:sonora/views/appbar/sj_appbar.dart';
import 'package:sonora/views/dialog/sj_medal_obtain_dailog.dart';
import '../../bloc/home/sj_home_bloc.dart';
import '../../config/sj_app_initial.dart';
import '../../models/sj_login_response_data.dart';
import '../../models/sj_works_model.dart';
import '../../utils/sj_media_util.dart';

@RoutePage()
class SjArticlePublishPage extends StatefulWidget {
  const SjArticlePublishPage({super.key});

  @override
  State<SjArticlePublishPage> createState() => _SjArticlePublishPageState();
}

class _SjArticlePublishPageState extends State<SjArticlePublishPage> {
  TextEditingController titleController = TextEditingController();
  TextEditingController contentController = TextEditingController();
  late final SjHomeBloc _homeBloc = getit<SjHomeBloc>();

  int maxTitleLength = 100;
  int maxContentLength = 500;

  List<String> postImageList = [];
  int postContentLength = 0;

  @override
  void initState() {
    super.initState();

    postImageList.clear();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: Scaffold(
        backgroundColor: const Color(0xFFF987C2),
        appBar: SjAppbar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          shadowColor: Colors.transparent,
          title: const Text(
            'Post Article',
            style: TextStyle(fontFamily: 'Galada', color: Colors.black),
          ),
          leading: IconButton(
            padding: const EdgeInsets.only(left: 20),
            onPressed: () {
              Navigator.pop(context);
            },
            icon: Image.asset('assets/images/nav_back.png'),
          ),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(
              height: 20,
            ),
            Container(
                decoration: BoxDecoration(
                  color: const Color(0xFFF8F8F8),
                  borderRadius: BorderRadius.circular(4),
                ),
                padding: const EdgeInsets.only(left: 8),
                margin: const EdgeInsets.only(bottom: 18, left: 20, right: 20),
                child: TextField(
                  style: const TextStyle(
                    fontFamily: 'Galada',
                  ),
                  decoration: const InputDecoration(
                    hintText: 'Type your title.',
                    border: InputBorder.none,
                  ),
                  maxLines: 1,
                  controller: titleController,
                  onChanged: (value) {
                    if (value.length >= maxTitleLength) {
                      titleController.text = value.substring(0, maxTitleLength);
                      titleController.selection = TextSelection.fromPosition(
                          TextPosition(offset: titleController.text.length));
                    }
                  },
                )),
            Container(
              margin: const EdgeInsets.only(bottom: 18, left: 20, right: 20),
              child: Stack(children: [
                Container(
                    decoration: BoxDecoration(
                      color: const Color(0xFFF8F8F8),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    height: 132,
                    padding: const EdgeInsets.only(left: 8),
                    child: TextField(
                      style: const TextStyle(
                        fontFamily: 'Galada',
                      ),
                      decoration: const InputDecoration(
                        hintText: 'Start Your Creation...',
                        border: InputBorder.none,
                      ),
                      maxLines: 10,
                      controller: contentController,
                      onChanged: (value) {
                        if (value.length >= maxContentLength) {
                          contentController.text =
                              value.substring(0, maxContentLength);
                          contentController.selection =
                              TextSelection.fromPosition(TextPosition(
                                  offset: contentController.text.length));
                          return;
                        }
                        postContentLength = value.length;
                        setState(() {});
                      },
                    )),
                Positioned(
                  right: 10,
                  bottom: 10,
                  child: Text(
                    '$postContentLength/$maxContentLength',
                    style: const TextStyle(
                        color: Color(0x4D000000), fontFamily: 'Galada'),
                  ),
                ),
              ]),
            ),
            buildPicWidget(),
          ],
        ),
        bottomNavigationBar: Container(
          height: 100,
          alignment: Alignment.center,
          margin: const EdgeInsets.only(left: 40, right: 40),
          padding: const EdgeInsets.only(bottom: 30),
          child: GestureDetector(
            onTap: post,
            child: Container(
              width: double.infinity,
              height: 60,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(40),
              ),
              child: const Text(
                'POST',
                style: SjTextStyle.customFontTheme16,
              ),
            ),
          ),
        ),
      ),
    );
  }

  void post() async {
    if (titleController.text.isEmpty) {
      EasyLoading.showToast('Please input title.');
      return;
    }
    if (contentController.text.isEmpty) {
      EasyLoading.showToast('Please input content.');
      return;
    }
    if (postImageList.isEmpty) {
      EasyLoading.showToast('Please add image.');
      return;
    }
    await _homeBloc.postArticle(
      titleController.text,
      contentController.text,
      postImageList,
    );
    // Navigator.pop(context);
    // first posrt show medal dialog
    bool firstComment = await SjStorageUtils.getUserFirstPostKey();
    if (firstComment && mounted) {
      showDialog(
          barrierDismissible: false,
          context: context,
          builder: (BuildContext buildContext) {
            return SjMedalObtainDialog(
              assetPath: 'assets/images/xz_bg_2.png',
              content: 'Congratulations on your new medal!',
              onAgree: () {
                SjMedalUtils.instance.updateMedalIsObtain(true, 1);
                Navigator.pop(context);
              },
              onCancel: () {},
            );
          });
    } else {
      Navigator.pop(context);
    }
  }

  void addPostImage() async {
    var photosStatus = await Permission.photos.status;
    if (photosStatus.isDenied) {
      PermissionStatus result = await Permission.photos.request();
      if (result.isDenied || result.isPermanentlyDenied) {
      EasyLoading.showToast('You have not authorised this permission.',
          duration: const Duration(seconds: 3));
        return;
      }
    } else if (photosStatus.isPermanentlyDenied) {
      EasyLoading.showToast('You have not authorised this permission.',
          duration: const Duration(seconds: 3));
      return;
    }
    String? imgPath = await SjMediaUtil.instance.pickImage();
    if (imgPath != null) {
      Directory directory = await getTemporaryDirectory();
      String name = imgPath.split('/').last;
      SjLoginData? loginData = await SjStorageUtils.getLoginInfo();

      String destPath =
          '${directory.path}/article/${loginData!.userInfo!.userId!}/$name';
      await copyFile(imgPath, destPath);
      postImageList.add(destPath);
      setState(() {});
    }
  }

  static Future<bool> copyFile(String srcPath, String destPath) async {
    try {
      File source = File(srcPath);
      File destination = File(destPath);
      await destination.create(recursive: true);
      File file = await source.copy(destination.path);
      if (file.existsSync()) {
        return true;
      }
    } catch (e, s) {}
    return false;
  }

  buildPicWidget() {
    Widget addWidget = GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        addPostImage();
      },
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: const Color(0xFFF8F8F8),
          borderRadius: BorderRadius.circular(4),
        ),
        margin: const EdgeInsets.only(top: 12, bottom: 32, left: 20, right: 20),
        width: 104,
        height: 110,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
          ),
          child: const Icon(
            Icons.add,
            color: Color(0xFFCCCCCC),
            size: 100,
          ),
        ),
      ),
    );

    List<Widget> children = [];
    for (var item in postImageList) {
      children.add(Container(
        margin: const EdgeInsets.only(top: 12, bottom: 32, left: 20, right: 20),
        child: Stack(children: [
          SizedBox(
            width: 104,
            height: 110,
            child: Image.file(
              File(item),
              fit: BoxFit.fill,
            ),
          ),
          Positioned(
            right: 0,
            top: 0,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                postImageList.remove(item);
                setState(() {});
              },
              child: SizedBox(
                width: 30,
                height: 20,
                child: SvgPicture.asset('assets/images/find_post_del.svg'),
              ),
            ),
          ),
        ]),
      ));
    }

    if (children.length < 3) {
      children.add(addWidget);
    }
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: children,
      ),
    );
  }
}
